import {
	BitSet,
	BitClr,
	Set2Byte,
	DataGet,
	ab2hex,
	hexCharCodeToStr,
	arrayToBuffer,
	Parse,
	Set3Byte,
	bitToStr,
	Set1Byte,
	feedback,
	Set4Byte,
	Get2Byte,
	Get4Byte,
	Get3Byte,
	getByBite,
	uploadEquipCommlog,
} from "@/utils/index.js";
import {
	serviceId,
	characteristicId2,
} from "@/utils/service.js";

import {
	READ_AND_WRITE_STATUS,
} from "@/common/config.js";
export default {
	data() {
		return {
			startTime: null, //开始时间戳
		}
	},
	methods: {
		isRead() {
			let that = this;
			uni.showModal({
				title: '提示',
				content: '确定要查询吗？',
				success(res) {
					if (res.confirm) {
						that.doRead();
					}
				}
			})
		},
		// 一键诊断 读取设备信息
		async doRead(addr) {
			let that = this;
			that.$Toast.loading('查询中~');
			this.startTime = new Date().getTime();

			let datas = DataGet(this.command, 0, addr ? addr : 0, 0, 0, null);
			let buffer = arrayToBuffer(datas);

			let requestHex = ab2hex(buffer);
			let {
				deviceId,
			} = this.deviceInfo;
			uni.writeBLECharacteristicValue({
				deviceId,
				serviceId,
				characteristicId: characteristicId2,
				// 这里的value是ArrayBuffer类型
				value: buffer,
				success(res) {
					setTimeout(() => {
						that.doCharData(addr);
					}, 300)

					uploadEquipCommlog(requestHex, '', READ_AND_WRITE_STATUS[1], 1, that.startTime,
						that.deviceInfo, that.dgMessage);
				},
				fail(err) {
					console.log(err)
					that.$Toast.none(`${that.dgMessage}检测失败!`);
					uploadEquipCommlog(requestHex, '', READ_AND_WRITE_STATUS[1], 0, that.startTime,
						that.deviceInfo, that.dgMessage);
				}
			})
		},
		// 读取数据
		doCharData(addr) {
			let {
				deviceId
			} = this.deviceInfo;
			let that = this;
			this.startTime = new Date().getTime();

			// 读取低功耗蓝牙设备的特征值的二进制数据值
			uni.readBLECharacteristicValue({
				deviceId,
				serviceId,
				characteristicId: characteristicId2,
				success(res) {
					uni.onBLECharacteristicValueChange(function(res) {
						uni.hideLoading();
						// 解析数据
						const uint8Array = new Uint8Array(res.value);
						const newArray = Array.from(uint8Array);
						let databuff = Parse(newArray);

						uploadEquipCommlog('', ab2hex(res.value), READ_AND_WRITE_STATUS[0], 1, that
							.startTime,
							that.deviceInfo, that.dgMessage);

						if (databuff && (databuff.dataUnit || databuff.dataUnit == 0)) {
							switch (databuff.dataUnit) {
								//数据单元 0：主控单元;1：检测单元;2：仓控单元;3：柜控电源单元;4：整流电源单元;5：电池单元;6：消防单元;7：充电电源
								case 0:
									if (databuff.databuff && databuff.databuff.length == 29) {
										for (let i = 0; i < 4; i++) {
											that.masterControl[`param${i+1}`] = databuff.databuff[i];
										}

										let str5 = ab2hex(res.value.slice(11, 31));
										that.masterControl.param5 = hexCharCodeToStr(str5);

										that.masterControl.param6 = databuff.databuff[24];
										that.masterControl.param7 = Get4Byte(databuff.databuff.slice(25,
											29));
									}
									break;
								case 1:
									if (databuff.databuff && databuff.databuff.length == 21) {
										for (let i = 0; i < 3; i++) {
											that.unitInfo[`param${i+1}`] = databuff.databuff[i];
										}

										let param4 = Get2Byte(databuff.databuff.slice(3,
											5));
										that.unitInfo.param4 = (param4 / 10).toFixed(1);

										that.unitInfo.param5 = databuff.databuff[5];
										that.unitInfo.param6 = databuff.databuff[6];

										let param7 = Get4Byte(databuff.databuff.slice(7,
											11));
										that.unitInfo.param7 = (param7 / 100)
											.toFixed(2);

										let param8 = Get2Byte(databuff.databuff.slice(11, 13));
										that.unitInfo.param8 = (param8 / 10)
											.toFixed(1);

										let param9 = Get2Byte(databuff.databuff.slice(13, 15));
										that.unitInfo.param9 = (param9 / 10)
											.toFixed(1);

										let param10 = Get2Byte(databuff.databuff.slice(15,
											17));
										that.unitInfo.param10 = (param10 / 10)
											.toFixed(1);

										let param11 = databuff.databuff.slice(17, 21);
										// 4字节按位取出
										let arr11 = [...getByBite(param11[0]), ...getByBite(param11[1]),
											...
											getByBite(param11[2]), ...getByBite(param11[3])
										];
										for (let i = 0; i < 15; i++) {
											that.unitInfo[`param${i+11}`] = arr11[i];
										}
									}
									break;
								case 2:
									if (databuff.databuff && databuff.databuff.length == 28) {
										that.binStatus.param1 = databuff.databuff[0];

										let param2 = Get4Byte(databuff.databuff.slice(1, 5));
										that.binStatus.param2 = (param2 / 100).toFixed(2);

										let param3 = Get4Byte(databuff.databuff.slice(5, 9));
										that.binStatus.param3 = (param3 / 100).toFixed(2);

										let param4 = Get4Byte(databuff.databuff.slice(9, 13));
										that.binStatus.param4 = (param4 / 10).toFixed(1);

										let param5 = Get4Byte(databuff.databuff.slice(13, 17));
										that.binStatus.param5 = (param5 / 1000).toFixed(3);

										for (let i = 6; i < 9; i++) {
											that.binStatus[`param${i}`] = databuff.databuff[i + 11];
										}
										// 1位小数，有符号
										let param9 = Get2Byte(databuff.databuff.slice(20, 22));
										that.binStatus.param9 = (param9 / 10).toFixed(1);

										let str5 = hexCharCodeToStr(ab2hex(res.value.slice(23, 25)));
										that.masterControl.param5 = (Number(str5) / 10).toFixed(1);

										that.binStatus.param10 = databuff.databuff[22];
										that.binStatus.param11 = databuff.databuff[23];

										let param12 = databuff.databuff.slice(24, 28);
										// 4字节按位取出
										let arr12 = [...getByBite(param12[0]), ...getByBite(param12[1]),
											...
											getByBite(param12[2]), ...getByBite(param12[3])
										];
										for (let i = 0; i < 14; i++) {
											that.binStatus[`param${i+12}`] = arr12[i];
										}
									}
									break;
							}
						}
					})

				},
				fail(fal) {
					console.log("读取数据数据失败", fal)
					that.$Toast.none(`${that.dgMessage}检测失败!`);

					uploadEquipCommlog('', fal.errCode, READ_AND_WRITE_STATUS[0], 0, that.startTime,
						that.deviceInfo, that.dgMessage);
				}
			})
		},
		// 仓状态详情
		binPopup(index) {
			this.$refs.binpopup.open('center');
			this.currentIndex = index + 1;
			this.currentCollapse = 1;
			this.command = 2;
			this.dgMessage = `${this.currentIndex}号仓`;

			for (let key of Object.keys(this.binStatus)) {
				this.binStatus[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},
		unitPopup(index) {
			this.$refs.unitpopup.open('center');
			this.currentIndex = index + 1;
			this.command = 1;
			this.dgMessage = `检测单元${this.currentIndex}`;

			for (let key of Object.keys(this.unitInfo)) {
				this.unitInfo[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},
		// 数据单元
		detailCommand() {
			// currentCollapse:0,主控单元;1,仓状态;2,检测单元状态信息;3,柜控电源;4,整流电源;5,充电电源;6,电池
			switch (this.command) {
				case 0:
					this.dgMessage = "主控单元";
					break;
				case 1:
					this.dgMessage = "检测单元";
					break;
			}
		},
		detailData() {
			switch (this.type) {
				case "0":
					this.paramTitle = "主控单元";
					this.command = 0;
					break;
				case "1":
					this.paramTitle = "仓控单元";
					this.command = 2;
					if (this.index || this.index == 0) {
						this.paramTitle += `(${this.index+1}号仓)`
					}
					break;
				case "2":
					this.paramTitle = "检测单元";
					if (this.index || this.index == 0) {
						this.paramTitle += `${this.index+1}`
					}
					this.command = 1;
					break;
			}
			this.dgMessage = this.paramTitle;
		},
	},
}